<script setup>
import EditContainer from "@/components/AdminConponents/EditContainer.vue";
import {useRoute, useRouter} from "vue-router";
import {onMounted, ref, watch} from "vue";
import {gameGetAPI} from "@/api/AdminApi/game.js";
import {categoriesGetAllAPI, gameCategoryEditAPI} from "@/api/AdminApi/category.js";
import 'element-plus/theme-chalk/el-message.css'
import {ElMessage} from "element-plus";

const route = useRoute()
const categoryInfo = ref({
  gameId: null,
  categories: []
})
const gameName = ref()

const getGameInfo = async (id = route.params.id) => {
  const res = await gameGetAPI(id)
  /* eslint-disable no-unused-vars */
  const gameData = res.data
  categoryInfo.value.gameId = gameData.id
  categoryInfo.value.categories = gameData.gameCategory
  gameName.value = gameData.chineseName
}
onMounted(() => getGameInfo())

// 取消按钮
const router = useRouter()
const cancel = () => {
  router.go(-1)
}

// 删除分类
const handleDelete = (id) => {
  categoryInfo.value.categories = categoryInfo.value.categories.filter(category => category.id !== id);
}

// 修改按钮
const edit = async () => {
  if (categoryInfo.value.categories.length === 0) {
    ElMessage.error("至少需要一个分类");
  }
  const res = await gameCategoryEditAPI(categoryInfo.value)
  if (res.code === 1) {
    ElMessage.success("更新成功")
    router.go(-1)
  } else {
    ElMessage.error(res.msg)
  }
}

const AllCategories= ref([])
const dialogVisible = ref(false)
const categoryName = ref()
// 打开分类列表
const showAllCategories = () => {
  dialogVisible.value = true
}

// 对话框打开时
const handleOpen = async () => {
  categoryName.value = null
}

const timer = ref()
watch(categoryName, (newValue, oldValue) => {
  AllCategories.value = []
  clearTimeout(timer.value);
  timer.value = setTimeout(async () => {
    const res = await categoriesGetAllAPI(newValue)
    res.data.forEach(category => {
      // 检查当前分类是否已经存在于 AllCategories 中
      const existingCategory = categoryInfo.value.categories.find(c => c.id === category.id);
      if (!existingCategory) {
        // 如果当前分类不存在于 AllCategories 中，则添加到 AllCategories 中
        AllCategories.value.push(category);
      }
    });
  }, 300);
}, { deep: true, immediate: true });

// 添加分类
const addCategory = (newCategory) => {
  categoryInfo.value.categories.push(newCategory)
  dialogVisible.value = false
  AllCategories.value = AllCategories.value.filter(category => category.id !== newCategory.id);
}
</script>

<template>
  <EditContainer :title="`${gameName}游戏分类编辑`">
    <template #body>
      <el-form>
        <el-form-item label="关联分类">
          <el-tag
              v-for="(category, index) in categoryInfo.categories"
              :key="index"
              style="margin-right: 5px;"
              closable
              size="large"
              @close="handleDelete(category.id)">
            {{ category.name }}
          </el-tag>
          <el-button type="success" @click="showAllCategories">
            + 添加分类
          </el-button>
        </el-form-item>
      </el-form>
    </template>
    <template #footerLeft>
      <el-button class="button" @click="cancel" type="info">取消</el-button>
    </template>
    <template #footerRight>
      <el-button class="button" @click="edit" type="primary">修改</el-button>
    </template>
  </EditContainer>
  <el-dialog
      width="500px"
      @open="handleOpen"
      draggable
      v-model="dialogVisible">
    <span>分类名:&nbsp;&nbsp;</span>
    <el-input v-model="categoryName" style="width: 240px" placeholder="请输入分类名" />
    <el-scrollbar height="300px">
      <el-button
          type="primary"
          v-for="item in AllCategories"
          style="margin: 10px"
          @click="addCategory(item)"
          :key="item">
        {{ item.name }}
      </el-button>
    </el-scrollbar>
  </el-dialog>
</template>

<style scoped>
</style>
